using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;

namespace Babylon.Toolbox
{
    partial class StatesManager
    {
        readonly int[] currentSamplerKey = new int[8];
        readonly TextureAddressMode[] uAddressMode = new TextureAddressMode[8];
        readonly TextureAddressMode[] vAddressMode = new TextureAddressMode[8];
        readonly Dictionary<int, SamplerState> samplerStates = new Dictionary<int, SamplerState>();

        int ComputeSamplerKey(int index)
        {
            return (((int)uAddressMode[index]) << 3) + ((int)vAddressMode[index]);
        }

        public TextureAddressMode GetUAddressMode(int index)
        {
            return uAddressMode[index];
        }

        public void SetUAddressMode(int index, TextureAddressMode value)
        {
            uAddressMode[index] = value;
        }

        public TextureAddressMode GetVAddressMode(int index)
        {
            return vAddressMode[index];
        }

        public void SetVAddressMode(int index, TextureAddressMode value)
        {
            vAddressMode[index] = value;
        }

        public void ApplySamplerState(int index)
        {
            int key = ComputeSamplerKey(index);

            if (key == currentSamplerKey[index])
                return;

            SamplerState samplerState;

            if (!samplerStates.TryGetValue(key, out samplerState))
            {
                samplerState = new SamplerState
                                   {
                                       Filter = TextureFilter.Linear,
                                       AddressU = uAddressMode[index],
                                       AddressV = vAddressMode[index],
                                   };

                samplerStates.Add(key, samplerState);
            }

            currentSamplerKey[index] = key;
            Device.SamplerStates[index] = samplerState;
        }
    }
}
